package tests;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

class TestServer implements Runnable {
	
	private String response1;
	private String response2;
	private String request = "";
	private final int port;
	
	public TestServer(String response, int port) {
		this.response1 = response;
		this.port = port;
	}
	
	public void setResponse(String res) {
		response2 = res;
	}
	
	public String getRequest() {
		return request;
	}
	
	public void run() {
		if (!request.isEmpty())
			return;
		
		
		Socket sock = null;
		ServerSocket ss = null;
		
		try {
			ss = new ServerSocket(port);
			ss.setSoTimeout(10000);
			sock = ss.accept();
			
			Scanner scan = new Scanner(sock.getInputStream());
			String tmp = null;
			do {
				tmp = scan.nextLine().trim();
				request += tmp + "\r\n";
			} while (!tmp.isEmpty());
			
			sock.getOutputStream().write(response1.getBytes());
			sock.getOutputStream().flush();
			
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try { sock.close(); } catch (Exception e) {}
			try { ss.close(); } catch (Exception e) {}
		}
		
	}
}